﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
using RMS.Common;
using RMS.DB;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Xml;
using System.Drawing.Printing;
using Microsoft.Office.Interop.Word;

//using DocumentFormat.OpenXml.Packaging;
//using DocumentFormat.OpenXml.Spreadsheet;
//using DocumentFormat.OpenXml;
//using DocumentFormat.OpenXml.Wordprocessing;


namespace RMS
{
    public partial class frmSellInventory : ICommonForm
    {
        //
        //
        private readonly CustomersMng customersMng = new CustomersMng();
        private readonly Invoice draftInvoice;
        private readonly InventoryMng inventoryMng = new InventoryMng();
        private readonly InvoicesMng invoicesMng = new InvoicesMng();
        private readonly SoldItemsMng soldItemsMng = new SoldItemsMng();
        private readonly SupplierMng supplierMng = new SupplierMng();
        private string[] _customerInfo = new string[7];
        private decimal _totalCost = 0;
        private decimal _totalQty = 0;
        private string draftOrderCode;
        private List<Inventory> listCart;
        private string _curentSelectedItemPrice;

        private System.Drawing.Font printFont;
        private StreamReader streamToPrint;


        private bool IsDiscount = false;
        private decimal PercentDiscount = 0;

        public frmSellInventory()
        {
            InitializeComponent();
            listCart = new List<Inventory>();
        }

        public frmSellInventory(Invoice _draft)
        {
            InitializeComponent();
            listCart = new List<Inventory>();
            draftInvoice = _draft;
        }

        private void frmSellInventory_Load(object sender, EventArgs e)
        {
            txtTotalCost.Enabled = Utilities.IsEnableSaleprice();
            txtSaleInvoice.Text = OrderCodeGenerating();
            BindAllInventory();
            gridCart.AutoGenerateColumns = false;
            btnSaveDraft.Enabled = false;
            txtID.Focus();
            if (draftInvoice != null)
            {
                BindDraftData(draftInvoice);
                draftOrderCode = draftInvoice.OrderCode;
            }
            gridInventoryList.ClearSelection();
        }

        private void BindDraftData(Invoice item)
        {
            List<SoldItem> listSoldItem = soldItemsMng.GetListItems(item.OrderCode);

            // Load customer
            var customer = customersMng.GetItemByDraftOrder(item.OrderCode);
            if (customer != null)
            {
                _customerInfo[0] = customer.ID;
                _customerInfo[1] = txtCusName.Text = customer.Name;
                _customerInfo[2] = customer.Address;
                _customerInfo[3] = customer.PhoneNo;
                _customerInfo[4] = customer.Email;
                _customerInfo[5] = Convert.ToBoolean(customer.IsVip) ? "True" : "False";
                _customerInfo[6] = customer.VipCode;
            }

            // load cart
            List<Inventory> newList = new List<Inventory>();
            foreach (SoldItem soldItem in listSoldItem)
            {
                var invItem = new Inventory
                {
                    ID = soldItem.ProductID,
                    Name = soldItem.Name,
                    ImportPrice = soldItem.ImportPrice.HasValue ? soldItem.ImportPrice.Value : 0,
                    ExportPrice = soldItem.ExportPrice.HasValue ? soldItem.ExportPrice.Value : 0,
                    ExportQuantity = soldItem.ExportQuantity.HasValue ? soldItem.ExportQuantity.Value : 0,
                    ExportWeight = soldItem.ExportWeight.HasValue ? soldItem.ExportWeight.Value : 0,
                    Quantity = soldItem.ImportQuantity.HasValue ? soldItem.ImportQuantity.Value : 0,
                    Weight = soldItem.ImportWeight.HasValue ? soldItem.ImportWeight.Value : 0
                };

                listCart.Add(invItem);
                

                _totalQty += Convert.ToInt32(soldItem.ExportQuantity);
                _totalCost += Convert.ToDecimal(soldItem.ExportPrice);
            }
            txtTotalProduct.Text = Convert.ToString(_totalQty);
            txtTotalPrice.Text = Utilities.FormatNumber(Convert.ToDecimal(_totalCost), Utilities.PrecisionFormat);
            if (listCart != null)
            {

                gridCart.DataSource = listCart;
            }

            decimal discount = item.Discount.HasValue ? item.Discount.Value : 0;

            if (discount != 0)
            {
                PercentDiscount = discount;
                txtDiscountTotal.Text = Utilities.FormatNumber(_totalCost - (_totalCost * Convert.ToDecimal(discount) / 100), Utilities.PrecisionFormat);
                if (customer != null)
                    txtVipCodeCheck.Text = customersMng.GetVipCode(customer.ID);
                lblDiscount.Text = String.Format("{0} % = {1}", item.Discount, Utilities.FormatNumber((_totalCost * Convert.ToDecimal(item.Discount) / 100), Utilities.PrecisionFormat));
            }
            else
            {
                txtDiscountTotal.Text = txtTotalPrice.Text;
            }
        }

        private void BindAllInventory()
        {
            List<Inventory> src = inventoryMng.GetRemainInStockInventory();
            gridInventoryList.AutoGenerateColumns = false;
            gridInventoryList.DataSource = src;
        }

        private void BindDataToTextbox(string name, string volume, string code, string supplier, string cate, string styleno, string metal,
        string image, string importPrice, string weight, decimal quantity, string supplyInvoiceNo, string itemNo, string memoNo, string supplyStyleNo)
        {
            txtID.Text = code;
            txtCategory.Text = cate;
            txtSalePrice.Text =
            txtTotalCost.Text = Utilities.FormatNumber(Convert.ToDecimal(metal), Utilities.PrecisionFormat);
            txtStyleNo.Text = styleno;
            txtSupply.Text = supplier;
            txtName.Text = name;
            txtVolume.Text = Utilities.FormatNumber(Convert.ToDecimal(volume), 0);
            //lblCalImportPrice
            lbImportPrice.Text = importPrice;
            txtRemainWeight.Text = Utilities.FormatNumber(Convert.ToDecimal(weight), 2);
            //var convertedVal = Convert.ToDecimal(weight) / (decimal)Constants.GoldConst;
            //txtRemainChi.Text = Utilities.FormatNumber(convertedVal, 3);
            txtRemainQty.Text = Convert.ToString(quantity);

            txtInvoiceNo.Text = supplyInvoiceNo;
            txtMemoNo.Text = memoNo;
            txtItemNo.Text = itemNo;
            txtSupStyleNo.Text = supplyStyleNo;

            //if (!string.IsNullOrEmpty(txtRemainQty.Text) && Convert.ToInt32(txtRemainQty.Text) == 1)
            //{
            //    //txtWeight.Text = txtRemainWeight.Text;
            //    //txtChiVang.Text = txtRemainChi.Text;
            //    if (!string.IsNullOrEmpty(txtImportPrice.Text) && !string.IsNullOrEmpty(txtQuantity.Text))
            //    {
            //        var total = Convert.ToDouble(txtImportPrice.Text) * Convert.ToDouble(txtQuantity.Text.Trim());
            //        lblCalImportPrice.Text = Utilities.FormatNumber(Convert.ToDecimal(total), Utilities.PrecisionFormat);
            //    }
            //}
            //else
            //{
            //    lblCalImportPrice.Text = "0";
            //    //txtWeight.Text =
            //    //txtChiVang.Text = "";
            //}

            _curentSelectedItemPrice = Convert.ToString(txtTotalCost.Text.Trim());
            if (!string.IsNullOrEmpty(txtVipCodeCheck.Text) && IsDiscount)
            {
                txtTotalCost.Text = Utilities.FormatNumber(Convert.ToDecimal(txtTotalCost.Text) - Convert.ToDecimal(txtTotalCost.Text) * Convert.ToDecimal(PercentDiscount) / 100, Utilities.PrecisionFormat);
            }

            var imageFilePath = String.Format("{0}\\{1}{2}", Environment.CurrentDirectory, Constants.ImageFilePath, image);
            if (File.Exists(imageFilePath))            
                itemImage.Image = Image.FromFile(imageFilePath);
            else
                itemImage.Image = null;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            Inventory item = inventoryMng.GetInventoryByElements(txtID.Text.Trim());
            if (item == null)
            {
                MessageBox.Show(Constants.Msg.NotItemExist);
                ClearAllTextbox();
                return;
            }
            BindDataToTextbox(item.Name, Convert.ToString(item.Volume), item.ID, item.SupplierID, item.Category, item.StyleId, Convert.ToString(item.SalePrice), item.Image,
            Convert.ToString(item.ImportPrice), Convert.ToString(item.Weight), Convert.ToDecimal(item.Quantity), item.InvoiceNo, item.ItemNo, item.MemoNo, item.StyleNo);

            AddToCard(item);
            txtID.Focus();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(Constants.Msg.ConfirmClose, "Chú ý", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (!string.IsNullOrEmpty(draftOrderCode))
                {
                    frmListDraftInvoices frm = new frmListDraftInvoices() { MdiParent = frmMain.ActiveForm, WindowState =  FormWindowState.Maximized };
                    frm.Show();
                }
                Close();
            }
        }

        private void btnCart_Click(object sender, EventArgs e)
        {
            if (CheckRequiredField())
            {
                var item = inventoryMng.GetInventoryByElements(txtID.Text.Trim());
                if (item == null)
                {
                    MessageBox.Show(Constants.Msg.NotItemExist, "Chú ý");
                    txtID.Focus();
                    return;
                }

                AddToCard(item);
                ClearAllTextbox();
                
            }
        }

        private void AddToCard(Inventory item)
        {
            foreach (DataGridViewRow row in gridCart.Rows)
            {
                if (item.ID == Convert.ToString(row.Cells[0].Value))
                {
                    var old = Convert.ToInt32(row.Cells[2].Value);
                    var newQty = old + Convert.ToInt32(txtQuantity.Text.Trim());
                    if (newQty > Convert.ToInt32(item.Quantity))
                    {
                        row.Cells[2].Value = item.Quantity;
                        row.Cells[3].Value = Convert.ToDecimal(row.Cells[3].Value) / old * Convert.ToDecimal(row.Cells[2].Value);
                    }
                    else
                    {
                        row.Cells[2].Value = newQty;
                        var newPrice = Convert.ToDecimal(row.Cells[3].Value) / old * Convert.ToDecimal(row.Cells[2].Value);
                        row.Cells[3].Value = newPrice;
                    }

                    decimal totalprice = 0;
                    decimal totalquantity = 0;
                    foreach (DataGridViewRow row1 in gridCart.Rows)
                    {
                        totalquantity += Convert.ToDecimal(row1.Cells[2].Value);
                        totalprice += Convert.ToDecimal(row1.Cells[3].Value);
                    }
                    _totalCost = totalprice;
                    _totalQty = totalquantity;
                    txtTotalProduct.Text = Convert.ToString(totalquantity);
                    txtTotalPrice.Text = Utilities.FormatNumber(totalprice, Utilities.PrecisionFormat);
                    if (!string.IsNullOrEmpty(txtVipCodeCheck.Text.Trim()) && PercentDiscount != 0)
                    {
                        var discountTotal = Convert.ToDecimal(txtTotalPrice.Text) -
                        (Convert.ToDecimal(txtTotalPrice.Text) * PercentDiscount / 100);
                        txtDiscountTotal.Text = Utilities.FormatNumber(discountTotal, Utilities.PrecisionFormat);
                        lblDiscount.Text = String.Format("{0}% = {1}", PercentDiscount, Utilities.FormatNumber((Convert.ToDecimal(txtTotalPrice.Text) * PercentDiscount / 100), Utilities.PrecisionFormat));
                    }
                    else
                    {
                        txtDiscountTotal.Text = txtTotalPrice.Text;
                    }
                    //foreach (Inventory cartItem in listCart)
                    //{
                    //    if(cartItem.ID == item.ID)
                    //    {
                    //        cartItem.ExportQuantity = Convert.ToInt32(row.Cells[2].Value);
                    //        cartItem.ExportPrice = Convert.ToDecimal(row.Cells[3].Value);    
                    //        break;
                    //    }
                    //}                        
                    //if (listCart != null) listCart.Add(item);
                    return;
                }
            }
            item.ExportQuantity = Convert.ToInt32(txtQuantity.Text.Trim());
            item.ExportPrice = Convert.ToDecimal(_curentSelectedItemPrice);
            if (listCart != null)
                listCart.Add(item);

            _totalCost += Convert.ToDecimal(item.ExportPrice);
            _totalQty += Convert.ToDecimal(item.ExportQuantity);
            txtTotalPrice.Text = Utilities.FormatNumber(Convert.ToDecimal(_totalCost), Utilities.PrecisionFormat);
            txtTotalProduct.Text = Convert.ToString(_totalQty);

            List<Inventory> newList = new List<Inventory>();
            newList.AddRange(listCart);

            gridCart.DataSource = newList;
                        
            
            //IsDiscount = true;
            btnSaveDraft.Enabled = true;
            if (!string.IsNullOrEmpty(txtVipCodeCheck.Text.Trim()) && PercentDiscount != 0)
            {
                var discountTotal = Convert.ToDecimal(txtTotalPrice.Text) -
                (Convert.ToDecimal(txtTotalPrice.Text) * Convert.ToDecimal(PercentDiscount) / 100);
                txtDiscountTotal.Text = Utilities.FormatNumber(discountTotal, Utilities.PrecisionFormat);
            }
            else
            {
                txtDiscountTotal.Text = txtTotalPrice.Text;
            }
            lblDiscount.Text = PercentDiscount == 0 ? Utilities.FormatNumber(0, Utilities.PrecisionFormat) + "%" : String.Format("{0} % = {1}", PercentDiscount, Utilities.FormatNumber((Convert.ToDecimal(txtTotalPrice.Text) * Convert.ToDecimal(PercentDiscount) / 100), Utilities.PrecisionFormat));
        }

        private bool CheckRequiredField()
        {
            if (string.IsNullOrEmpty(txtID.Text.Trim()))
            {
                MessageBox.Show(Constants.Msg.ItemIdRequired, "Chú ý");
                txtID.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(txtTotalCost.Text.Trim()))
            {
                MessageBox.Show(Constants.Msg.ItemPriceRequired, "Chú ý");
                txtTotalCost.Focus();
                return false;
            }

            try
            {
                var x = Convert.ToDecimal(lbImportPrice.Text) * Convert.ToDecimal(txtQuantity.Text.Trim());
                var y = Convert.ToDecimal(txtTotalCost.Text.Trim());
                if (x > y)
                {
                    if (MessageBox.Show(Constants.Msg.PriceOutLessThanIn, "Chú ý", MessageBoxButtons.YesNo) == DialogResult.No)
                        return false;
                }
            }
            catch (FormatException)
            {
                return false;
            }
            return true;
        }

        private void ClearAllTextbox()
        {
            txtSalePrice.Text =
            txtID.Text =
            txtCategory.Text =
            txtName.Text =
            txtStyleNo.Text =
            txtSupply.Text =
            txtVolume.Text =
            txtRemainWeight.Text =
            txtRemainQty.Text =
            txtInvoiceNo.Text =
            txtMemoNo.Text =
            txtItemNo.Text =
            txtSupStyleNo.Text =
            txtTotalCost.Text = "";
            txtQuantity.Text = "1";
            itemImage.Image = null;
        }

        private void RemoveCartItem(DataGridViewRow rowToDelete)
        {
            int flag = gridCart.Rows.Cast<DataGridViewRow>().Count(row => Convert.ToBoolean(row.Selected));
            if (flag == 0)
            {
                MessageBox.Show(Constants.Msg.ChooseOneItem, "Chú ý");
                return;
            }

            if (MessageBox.Show(Constants.Msg.DropOutShopCart, "Chú ý", MessageBoxButtons.YesNo) != DialogResult.Yes)
                return;

            listCart.RemoveAt(rowToDelete.Index);

            List<Inventory> newList = new List<Inventory>();
            newList.AddRange(listCart);

            gridCart.DataSource = newList;


            _totalCost = 0;
            _totalQty = 0;
            foreach (DataGridViewRow row in gridCart.Rows)
            {
                _totalCost = _totalCost + Convert.ToDecimal(row.Cells[3].Value);
                _totalQty = _totalQty + Convert.ToDecimal(row.Cells[2].Value);
            }

            if (!string.IsNullOrEmpty(txtVipCodeCheck.Text.Trim()) && PercentDiscount != 0)
            {
                var discountTotal = Convert.ToDecimal(_totalCost) -
                (Convert.ToDecimal(_totalCost) * Convert.ToDecimal(PercentDiscount) / 100);
                txtDiscountTotal.Text = Utilities.FormatNumber(discountTotal, Utilities.PrecisionFormat);
                lblDiscount.Text = String.Format("{0}% = {1}", PercentDiscount, Utilities.FormatNumber((Convert.ToDecimal(_totalCost) * Convert.ToDecimal(PercentDiscount) / 100), Utilities.PrecisionFormat));
            }
            else
            {
                txtDiscountTotal.Text = Utilities.FormatNumber(_totalCost, Utilities.PrecisionFormat);
                ;
            }
        }

        private void AddCustomerInfo(decimal totalBuyingCost)
        {
            //if (_customerInfo[0] != null && !string.IsNullOrEmpty(txtCusName.Text.Trim()))
            //{
            //    Customer item = customersMng.get(_customerInfo[0]);
            //    //    customersMng.AddItem(_customerInfo[0], _customerInfo[1], _customerInfo[2], _customerInfo[3],
            //    //        _customerInfo[4], totalBuyingCost,(_customerInfo[5] == "True") ? true : false,_customerInfo[6]);
            //    //else
            //    if (item != null)
            //    {
            //        customersMng.UpdateItem(_customerInfo[6], totalBuyingCost);
            //    }
            //}
            if (!string.IsNullOrEmpty(txtVipCodeCheck.Text.Trim()))
            {
                var item = customersMng.GetItemByVipCode(txtVipCodeCheck.Text.Trim());
                if (item != null)
                    customersMng.UpdateItem(txtVipCodeCheck.Text.Trim(), totalBuyingCost);
            }
            else
                if (!string.IsNullOrEmpty(_customerInfo[0]))
                {
                    var item = customersMng.GetItemByElements(_customerInfo[0]);
                    if (item != null)
                        customersMng.UpdateItem(_customerInfo[0], totalBuyingCost, "");
                }
        }

        private void btnSell_Click(object sender, EventArgs e)
        {
            if (CheckRequiredField())
            {
                if (!string.IsNullOrEmpty(txtVipCodeCheck.Text.Trim()))
                {
                    if (!customersMng.CheckVipCode(txtVipCodeCheck.Text.Trim()))
                    {
                        MessageBox.Show("Mã thẻ Vip không đúng.\nXin vui lòng kiểm tra lại!", "Chú ý");
                        txtVipCodeCheck.Focus();
                        return;
                    }
                }
                if (string.IsNullOrEmpty(txtSaleInvoice.Text.Trim()))
                {
                    MessageBox.Show(Constants.Msg.SaleInvoiceRequired, "Chú ý");
                    txtSaleInvoice.Focus();
                    return;
                }

                QuickSaleItem();
                txtSaleInvoice.Text = OrderCodeGenerating();
            }
        }

        private PrintDataObject CollectDataToPrint(bool isQuickSale)
        {
            PrintDataObject printDataObject = new PrintDataObject();
            printDataObject.CustomerID = String.Format("{0} - {1}", txtCusName.Text, txtVipCodeCheck.Text);
            printDataObject.CustomerName = txtCusName.Text;
            printDataObject.InvoiceID = txtSaleInvoice.Text;

            List<PrintSoldItems> listData = new List<PrintSoldItems>();
            if (isQuickSale)
            {
                PrintSoldItems data = new PrintSoldItems() { Name = txtName.Text,
                Qty = txtQuantity.Value.ToString(),
                Price = txtSalePrice.Text,
                SubTotal = txtTotalCost.Text };
                listData.Add(data);

                printDataObject.TotalMoney = txtTotalCost.Text;
            }
            else
            {
                foreach (DataGridViewRow item in gridCart.Rows)
                {
                    int quantity = Convert.ToInt32(item.Cells[2].Value);
                    decimal subtotal = Convert.ToDecimal(item.Cells[3].Value);
                    decimal unitPrice = quantity == 0 ? 0 : subtotal / quantity;
                    PrintSoldItems data = new PrintSoldItems()
                    {
                        Name = item.Cells[1].Value.ToString(),
                        Qty = quantity.ToString(),
                        Price = Utilities.FormatNumber(unitPrice, Utilities.PrecisionFormat),
                        SubTotal = Utilities.FormatNumber(subtotal, Utilities.PrecisionFormat)
                    };

                    listData.Add(data);
                }

                printDataObject.TotalMoney = txtDiscountTotal.Text;
            }

            printDataObject.Discount = lblDiscount.Text;
            printDataObject.ListPrintSoldItems = listData;

            return printDataObject;
        }


        private void DoPrint(PrintDataObject printDataObject)
        {
            StreamReader readerPrintTemplate = null;
            try
            {
                string filePrintTemplate = Environment.CurrentDirectory + "\\PrintTemplate.htm";
                if (File.Exists(filePrintTemplate))
                {
                    string newRowHtmlFormat = @"<tr><td valign=top>{0}</td><td valign=top>{1}</td><td valign=top>{2}</td><td valign=top>{3}</td></tr>";
                    StringBuilder str = new StringBuilder();


                    foreach (PrintSoldItems item in printDataObject.ListPrintSoldItems)
                    {
                        String[] strTemp = { item.Name, item.Qty, item.Price, item.SubTotal };
                        str.AppendFormat(newRowHtmlFormat, strTemp);
                    }

                    ShopInfoManager shopInfoMng = new ShopInfoManager();
                    var shopinfo = shopInfoMng.GetOne();

                    var printContent = "";
                    using ( readerPrintTemplate = new StreamReader(filePrintTemplate))
                    {
                        printContent = readerPrintTemplate.ReadToEnd();
                    }

                    printContent = printContent.Replace("###Logo###", shopinfo.Logo);
                    printContent = printContent.Replace("###ShopName###", shopinfo.ShopName);
                    printContent = printContent.Replace("###Address###", shopinfo.Address);
                    printContent = printContent.Replace("###Phone###", shopinfo.Phone);
                    printContent = printContent.Replace("###Email###", shopinfo.Email);
                    printContent = printContent.Replace("###Website###", shopinfo.Website);

                    printContent = printContent.Replace("###DataToPrint###", str.ToString());
                    printContent = printContent.Replace("###CustNo###", printDataObject.CustomerID);
                    printContent = printContent.Replace("###InvoiceNo###", printDataObject.InvoiceID);
                    printContent = printContent.Replace("###TotalMoney###", printDataObject.TotalMoney);
                    printContent = printContent.Replace("###Discount###", printDataObject.Discount);

                    string filePrintMe = String.Format("{0}{1}Receipt_{2}.doc", Environment.CurrentDirectory, Constants.ReceiptsPath, txtSaleInvoice.Text.Trim());
                    filePrintMe = Path.GetFullPath(filePrintMe);
                    using (StreamWriter writer = new StreamWriter(filePrintMe))
                    {
                        writer.Write(printContent);
                        writer.Close();
                        //File.WriteAllText(filePrintMe, printContent);                        
                    }

                    //Print
                    Printing(filePrintMe);

                    //Old Print------
                    //var p = new ProcessStartInfo();
                    //p.Verb = "print";
                    //p.WindowStyle = ProcessWindowStyle.Hidden;
                    //p.FileName = filePrintMe;
                    //p.UseShellExecute = true;
                    //System.Diagnostics.Process.Start(p);
                }
                else
                {
                    MessageBox.Show("Khong tim thay file PrintTemplate.htm");
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                readerPrintTemplate.Close();
                readerPrintTemplate.Dispose();
            }
        }

        // The PrintPage event is raised for each page to be printed.
        private void pd_PrintPage(object sender, PrintPageEventArgs ev)
        {
            float linesPerPage = 0;
            float yPos = 0;
            int count = 0;
            float leftMargin = ev.MarginBounds.Left;
            float topMargin = ev.MarginBounds.Top;
            String line = null;

            // Calculate the number of lines per page.
            linesPerPage = ev.MarginBounds.Height /
            printFont.GetHeight(ev.Graphics);

            // Iterate over the file, printing each line.
            while (count < linesPerPage &&
            ((line = streamToPrint.ReadLine()) != null))
            {
                yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
                ev.Graphics.DrawString(line, printFont, Brushes.Black,
                leftMargin, yPos, new StringFormat());
                count++;
            }

            // If more lines exist, print another page.
            if (line != null)
                ev.HasMorePages = true;
            else
                ev.HasMorePages = false;
        }

        // Print the file.
        public void Printing(string filePath)
        {
            Microsoft.Office.Interop.Word.Document document = null;
            object filename = filePath;
            object missingValue = Type.Missing;

            try
            {
                // Create an Application object

                Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application() { /* I'm setting all of the alerts to be off as I am trying to get*/ /* this to print in the background*/
                DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone };

                // Open the document to print...

                // Using OpenOld so as to be compatible with other versions of Word
                document = app.Documents.OpenOld(ref filename,
                ref missingValue, ref missingValue,
                ref missingValue, ref missingValue, ref missingValue,
                ref missingValue, ref missingValue, ref missingValue, ref missingValue);

                // Set the active printer
                //app.ActivePrinter = "My Printer Name";

                object myTrue = true; // Print in background
                object myFalse = false;

                // Using PrintOutOld to be version independent

                app.ActiveDocument.PrintOut(ref myTrue,
                ref myFalse, ref missingValue, ref missingValue, ref missingValue,
                missingValue, ref missingValue,
                ref missingValue, ref missingValue, ref missingValue, ref myFalse,
                ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue);

                document.Close(ref missingValue, ref missingValue, ref missingValue);

                // Make sure all of the documents are gone from the queue
                while (app.BackgroundPrintingStatus > 0)
                {
                    System.Threading.Thread.Sleep(250);
                }

                app.Quit(ref missingValue, ref missingValue, ref missingValue);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
            finally
            {
                if (document != null)
                    document.Close(ref missingValue, ref missingValue, ref missingValue);
            }
        }

        private void QuickSaleItem()
        {
            string orderCode = OrderCodeGenerating();
            double importPrice = 0;
            decimal totalIm = 0;
            var item = inventoryMng.GetInventoryByElements(txtID.Text.Trim());
            if (item == null)
            {
                MessageBox.Show(Constants.Msg.NotItemExist, "Chú ý");
                txtID.Focus();
                return;
            }
            //if (!CheckStock(txtWeight.Text, Convert.ToDecimal(item.Weight)))
            //{
            //    txtWeight.Focus();
            //    return;
            //}
            if (IsExistInvoiceNo(txtSaleInvoice.Text.Trim()))
            {
                MessageBox.Show(Constants.Msg.InvoiceNoExist, "Chú ý");
                return;
            }
            if (MessageBox.Show(Constants.Msg.ConfirmSale, "Chú ý", MessageBoxButtons.YesNo) == DialogResult.No)
                return;
            inventoryMng.UpdateItem(item.ID, Convert.ToInt32(item.Quantity - Convert.ToInt32(txtQuantity.Text)));
            if (item.ImportPrice != null)
            {
                importPrice = Convert.ToDouble((Double) item.ImportPrice * (Convert.ToDouble(txtQuantity.Text)));
            }
            totalIm = Convert.ToDecimal(Math.Round(importPrice, 2));

            // Add customer
            AddCustomerInfo(Convert.ToDecimal(txtTotalCost.Text.Trim()));

            //Add invoice
            invoicesMng.AddNewItems(_customerInfo[0], txtSaleInvoice.Text.Trim(), orderCode, totalIm, Convert.ToDecimal(txtTotalCost.Text.Trim()),
            DateTime.Now, Constants.IsInventoryItem, false, Convert.ToDecimal(PercentDiscount));
            //Add sold item
            if (!string.IsNullOrEmpty(txtVipCodeCheck.Text.Trim()))
            {
                var cus = customersMng.GetItemByVipCode(txtVipCodeCheck.Text.Trim());
                _customerInfo[0] = cus.ID;
                _curentSelectedItemPrice = Convert.ToString(Convert.ToDecimal(_curentSelectedItemPrice) - Convert.ToDecimal(_curentSelectedItemPrice) * Convert.ToDecimal(PercentDiscount) / 100);
            }
            soldItemsMng.AddNewSoldItems(item.ID, item.Name, Constants.IsInventoryItem, orderCode,
            totalIm, Convert.ToInt32(item.Quantity), Convert.ToInt32(txtQuantity.Text.Trim()),
            Convert.ToDecimal(_curentSelectedItemPrice), 0,
            DateTime.Now, _customerInfo[0], txtSaleInvoice.Text.Trim());
            //Print invoice
            var dataToPrint = CollectDataToPrint(true);
            DoPrint(dataToPrint);

            MessageBox.Show(Constants.Msg.SaleSuccessful, "Chú ý");
            BindAllInventory();
            gridCart.DataSource = null;
            _totalQty = 0;
            _totalCost = 0;
            listCart = new List<Inventory>();
            _customerInfo = new string[7];
            btnSaveDraft.Enabled = false;
            txtCusName.Text  = draftOrderCode = "";
            txtTotalPrice.Text = txtTotalProduct.Text = "0";
            txtSaleInvoice.Text = "";
            txtCusName.Text = "";
            txtSaleInvoice.Text = txtVipCodeCheck.Text = "";
            ClearAllTextbox();
            IsDiscount = false;
        }

        private void btnBigSell_Click(object sender, EventArgs e)
        {
            if (listCart.Count < 1)
            {
                MessageBox.Show(Constants.Msg.SellerrorAlert, "Chú ý");
                return;
            }
            if (!string.IsNullOrEmpty(txtVipCodeCheck.Text.Trim()))
            {
                if (!customersMng.CheckVipCode(txtVipCodeCheck.Text.Trim()))
                {
                    MessageBox.Show("Mã thẻ Vip không đúng.\nXin vui lòng kiểm tra lại!", "Chú ý");
                    txtVipCodeCheck.Focus();
                    return;
                }
            }

            if (string.IsNullOrEmpty(txtSaleInvoice.Text.Trim()))
            {
                MessageBox.Show(Constants.Msg.SaleInvoiceRequired, "Chú ý");
                txtSaleInvoice.Focus();
                return;
            }
            if (IsExistInvoiceNo(txtSaleInvoice.Text.Trim()))
            {
                MessageBox.Show(Constants.Msg.InvoiceNoExist, "Chú ý");
                return;
            }
            AddToSoldItems();
        }

        private void AddToSoldItems()
        {
            if (listCart.Count == 0)
                return;
            if (MessageBox.Show(Constants.Msg.ConfirmSale, "Chú ý", MessageBoxButtons.YesNo) == DialogResult.No)
                return;
            string orderCode = OrderCodeGenerating();
            decimal totalIm = 0;
            decimal totalEx = 0;
            decimal itemImport;
            if (PercentDiscount == 0)
                totalEx = Convert.ToDecimal(txtTotalPrice.Text);
            if (PercentDiscount != 0)
                totalEx = Convert.ToDecimal(txtDiscountTotal.Text);
            double importPrice = 0;
            foreach (Inventory item in listCart)
            {
                itemImport = 0;
                var itemInStock = inventoryMng.GetInventoryByElements(item.ID);
                if (itemInStock.Quantity < item.ExportQuantity)
                {
                    MessageBox.Show(
                    "Số lượng sản phẩm [" + itemInStock.ID +
                    "] không đủ hàng trong kho.\nĐơn hàng này sẽ không được thực hiện", "Chú ý");
                    draftOrderCode = "";
                    return;
                }
                inventoryMng.UpdateItem(item.ID, Convert.ToInt32(itemInStock.Quantity - item.ExportQuantity));
                if (item.ImportPrice != null)
                {
                    importPrice =
                    Convert.ToDouble((Double) item.ImportPrice * item.ExportQuantity);
                }
                totalIm += Convert.ToDecimal(Math.Round(importPrice, 2));
                itemImport = Convert.ToDecimal(item.ImportPrice * item.ExportQuantity);
                //totalEx += Convert.ToDecimal(item.ExportPrice);


                // Delete old solditem if any)
                if (!string.IsNullOrEmpty(draftOrderCode))
                {
                    soldItemsMng.DeleteItem(item.ID, draftOrderCode);
                    //add sold items base on draft invoice
                    if (!string.IsNullOrEmpty(txtVipCodeCheck.Text.Trim()))
                    {
                        var cus = customersMng.GetItemByVipCode(txtVipCodeCheck.Text.Trim());
                        _customerInfo[0] = cus.ID;
                        item.ExportPrice =
                        Convert.ToDecimal(Convert.ToDecimal(item.ExportPrice) -
                        Convert.ToDecimal(item.ExportPrice) * Convert.ToDecimal(PercentDiscount) / 100);
                    }
                    soldItemsMng.AddNewSoldItems(item.ID, item.Name, Constants.IsInventoryItem, draftOrderCode,
                    itemImport, Convert.ToInt32(item.Quantity),
                    Convert.ToInt32(item.ExportQuantity),
                    Convert.ToDecimal(item.ExportPrice),
                    Convert.ToDecimal(item.ExportWeight),
                    DateTime.Now, _customerInfo[0], txtSaleInvoice.Text.Trim());
                }
                else
                {
                    //Add sold item
                    if (!string.IsNullOrEmpty(txtVipCodeCheck.Text.Trim()))
                    {
                        var cus = customersMng.GetItemByVipCode(txtVipCodeCheck.Text.Trim());
                        _customerInfo[0] = cus.ID;
                        item.ExportPrice =
                        Convert.ToDecimal(Convert.ToDecimal(item.ExportPrice) -
                        Convert.ToDecimal(item.ExportPrice) * Convert.ToDecimal(PercentDiscount) / 100);
                    }
                    soldItemsMng.AddNewSoldItems(item.ID, item.Name, Constants.IsInventoryItem, orderCode,
                    itemImport, Convert.ToInt32(item.Quantity),
                    Convert.ToInt32(item.ExportQuantity),
                    Convert.ToDecimal(item.ExportPrice),
                    Convert.ToDecimal(item.ExportWeight),
                    DateTime.Now, _customerInfo[0], txtSaleInvoice.Text.Trim());
                }
            }

            AddCustomerInfo(totalEx);
            if (string.IsNullOrEmpty(draftOrderCode) && !invoicesMng.IsExist(draftOrderCode))
                invoicesMng.AddNewItems(_customerInfo[0], txtSaleInvoice.Text.Trim(), orderCode, totalIm, totalEx, DateTime.Now,
                Constants.IsInventoryItem, false, Convert.ToDecimal(PercentDiscount));
            else
                invoicesMng.UpdateItem(draftOrderCode, _customerInfo[0], txtSaleInvoice.Text.Trim(), totalIm, totalEx, DateTime.Now, false);

            //Print invoice
            var dataToPrint = CollectDataToPrint(false);
            DoPrint(dataToPrint);
            MessageBox.Show(Constants.Msg.SaleSuccessful, "Chú ý");

            // Clear all and rebinddata
            BindAllInventory();
            gridCart.DataSource = null;

            _totalQty = 0;
            _totalCost = 0;
            listCart = new List<Inventory>();
            _customerInfo = new string[7];
            btnSaveDraft.Enabled = false;
            txtCusName.Text = draftOrderCode = "";
            txtSaleInvoice.Text = "";
            txtVipCodeCheck.Text = "";
            txtDiscountTotal.Text = "0";
            lblDiscount.Text = "0 %";
            PercentDiscount = 0;
            txtTotalPrice.Text = txtTotalProduct.Text = "0";
            ClearAllTextbox();
            IsDiscount = false;
            txtSaleInvoice.Text = OrderCodeGenerating();
        }

        private bool IsExistInvoiceNo(string currentNo)
        {
            var currentInvoice = invoicesMng.GetItemBySaleInvoiceNo(currentNo);
            if (currentInvoice == null)
                return false;
            return true;
        }


        private void btnSaveDraft_Click(object sender, EventArgs e)
        {
            if (listCart.Count == 0)
            {
                MessageBox.Show(Constants.Msg.AddtoCartDraft, "Chú ý");
                txtID.Focus();
                return;
            }

            string orderCode = OrderCodeGenerating();
            decimal totalIm = 0;
            decimal totalEx = 0;
            double importPrice = 0;
            var listProductId = "";
            foreach (Inventory item in listCart)
            {
                //Add draft item to database
                if (!string.IsNullOrEmpty(draftOrderCode))
                {
                    soldItemsMng.DeleteItem(item.ID, draftOrderCode);
                    //add sold items base on draft invoice
                    soldItemsMng.AddNewSoldItems(item.ID, item.Name, Constants.IsInventoryItem, draftOrderCode,
                    Convert.ToDecimal(item.ImportPrice), Convert.ToInt32(item.Quantity), Convert.ToInt32(item.ExportQuantity),
                    Convert.ToDecimal(item.ExportPrice), Convert.ToDecimal(item.ExportWeight),
                    DateTime.Now, "", "isdraft");
                }
                else
                    soldItemsMng.AddNewSoldItems(item.ID, item.Name, Constants.IsInventoryItem, orderCode,
                    Convert.ToDecimal(item.ImportPrice), Convert.ToInt32(item.Quantity), Convert.ToInt32(item.ExportQuantity),
                    Convert.ToDecimal(item.ExportPrice), Convert.ToDecimal(item.ExportWeight),
                    DateTime.Now, "", "isdraft");
                listProductId += ", " + Convert.ToString(item.ID);


                if (!string.IsNullOrEmpty(_customerInfo[0]))
                    customersMng.UpdateItem(_customerInfo[0], orderCode);
                if (item.ImportPrice != null)
                {
                    importPrice =
                    Convert.ToDouble((Double)item.ImportPrice * item.ExportQuantity);
                }
                totalIm += Convert.ToDecimal(Math.Round(importPrice, 2));
                totalEx += Convert.ToDecimal(item.ExportPrice);
            }

            // safe draft invoice and  list productId
            if (!string.IsNullOrEmpty(draftOrderCode))
            {
                invoicesMng.UpdateItem(draftOrderCode, "", listProductId.TrimStart(',', ' '), totalIm, totalEx, DateTime.Now, true);
            }
            else
                invoicesMng.AddNewItems("", listProductId.TrimStart(',', ' '), orderCode, totalIm, totalEx, DateTime.Now,
                Constants.IsInventoryItem, true, Convert.ToDecimal(PercentDiscount));
            //AddCustomerInfo(0);
            MessageBox.Show(Constants.Msg.SaveDraftSuccess, "Chú ý");
            _totalQty = 0;
            _totalCost = 0;
            listCart = new List<Inventory>();
            gridCart.DataSource = null;
            btnSaveDraft.Enabled = false;
            draftOrderCode = "";
            txtTotalPrice.Text = txtTotalProduct.Text = txtDiscountTotal.Text = "0";
            lblDiscount.Text = "0 %";
            txtSaleInvoice.Text = "";
            txtVipCodeCheck.Text = "";
            PercentDiscount = 0;
            IsDiscount = true;
            ClearAllTextbox();
        }

        private string OrderCodeGenerating() // dd-mo-yy-hh-mi-ss format
        {
            string code = "";
            string yy = DateTime.Now.Year.ToString().Substring(2, 2);
            string mo = DateTime.Now.Month.ToString("00");
            string dd = DateTime.Now.Day.ToString("00");
            string hh = DateTime.Now.Hour.ToString("00");
            string mi = DateTime.Now.Minute.ToString("00");
            string ss = DateTime.Now.Second.ToString("00");
            code = yy + mo + dd + hh + mi + ss;
            return code;
        }
        //private string SaleCodeGenerating() // yyMMddhhmm. format
        //{
        //    string code = "";
        //    string yy = DateTime.Now.Year.ToString().Substring(2, 2);
        //    string mo = DateTime.Now.Month.ToString("00");
        //    string dd = DateTime.Now.Day.ToString("00");
        //    string hh = DateTime.Now.Hour.ToString("00");
        //    string mi = DateTime.Now.Minute.ToString("00");            
        //    code = yy + mo + dd + hh + mi;
        //    return code;
        //}


        //private void gridCart_CellClick(object sender, DataGridViewCellEventArgs e)
        //{
        //    if (e.ColumnIndex == 4)
        //    {
        //        foreach (DataGridViewRow row in gridCart.Rows)
        //        {
        //            if (row.Cells[4].Selected)
        //            {
        //                row.Selected = true;
        //                RemoveCartItem();
        //                txtTotalPrice.Text = Utilities.FormatNumber(Convert.ToDecimal(_totalCost), Utilities.PrecisionFormat);
        //                txtTotalProduct.Text = Convert.ToString(_totalQty);
        //                break;
        //            }
        //        }
        //    }
        //}


        private void btnCustomerInfo_Click(object sender, EventArgs e)
        {
            var location = new frmInsertCustomerInfo();
            if (location.ShowDialog() == DialogResult.OK)
            {
                string[] arr = location.result.Split('#'); // get customer info arr           
                _customerInfo = arr;
                txtCusName.Text = arr[1];

                if (arr[5] == "True" && Utilities.IsSaleOff())
                {
                    txtVipCodeCheck.Text = arr[6];
                    txtVipCodeCheck.ForeColor = Color.DodgerBlue;
                    if (!string.IsNullOrEmpty(txtTotalCost.Text))
                    {
                        var discount = Convert.ToDecimal(Utilities.GetVipDiscount());
                        var cost = Convert.ToDecimal(txtSalePrice.Text.Trim()) - (Convert.ToDecimal(txtSalePrice.Text.Trim()) * discount / 100);
                        txtTotalCost.Text = Utilities.FormatNumber(cost, Utilities.PrecisionFormat);
                        IsDiscount = true;
                        PercentDiscount = discount;
                    }
                    txtVipCodeCheck.Focus();
                }
            }
        }

        private void validateNumeric(KeyPressEventArgs e)
        {
            char key = e.KeyChar;
            if ((key >= 48) && (key <= 58) || (key == 46) || key == 8 || key == 9 || (key >= 37 && key <= 40) || key == 144 || key == ',')
            {
                e.Handled = false;
            }
            else
                e.Handled = true;
        }

        private void txtWeight_KeyPress(object sender, KeyPressEventArgs e)
        {
            validateNumeric(e);
        }

        private void txtTotalCost_KeyPress(object sender, KeyPressEventArgs e)
        {
            validateNumeric(e);
        }

        private void txtTotalCost_Leave(object sender, EventArgs e)
        {
            try
            {
                var a = Convert.ToDecimal(txtTotalCost.Text.Trim());
            }
            catch (FormatException)
            {
                txtTotalCost.Text = "";
                return;
            }
            if (!string.IsNullOrEmpty(txtTotalCost.Text.Trim()))
            {
                _curentSelectedItemPrice = Convert.ToString(txtTotalCost.Text.Trim());
                txtTotalCost.Text = Utilities.FormatNumber(Convert.ToDecimal(txtTotalCost.Text), Utilities.PrecisionFormat);
            }
        }

        private void txtQuantity_Leave(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtSalePrice.Text) && !string.IsNullOrEmpty(txtQuantity.Text))
            {
                var total = Convert.ToDouble(txtSalePrice.Text) * Convert.ToDouble(txtQuantity.Text.Trim());
                txtTotalCost.Text = Utilities.FormatNumber(Convert.ToDecimal(total), Utilities.PrecisionFormat);
            }
            else
                txtTotalCost.Text = "0";
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            //if (dlgPrint.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //{
            //    LoadPrinterTemplate();
            //    string printstr = BuildBillForm();
            //    var printDoc = new PrintBill(printstr);
            //    printDoc.Print();
            //}


            // Create a Wordprocessing document. 
            //using (WordprocessingDocument package = WordprocessingDocument.Create("test.docx", WordprocessingDocumentType.Document))
            //{
            //    // Add a new main document part. 
            //    package.AddMainDocumentPart();

            //    // Create the Document DOM. 
            //    package.MainDocumentPart.Document =
            //      new Document(
            //        new Body(
            //          new Paragraph(
            //            new DocumentFormat.OpenXml.Wordprocessing.Run(
            //              new DocumentFormat.OpenXml.Wordprocessing.Text("Hello World!")))));


            //// Save changes to the main document part. 
            //package.MainDocumentPart.Document.Save();
            //} 

        }

        //private void LoadPrinterTemplate()
        //{
        //    var path = Path.Combine(Application.StartupPath, Properties.Resources.BillTemplate);
        //    if (File.Exists(path))
        //    {
        //        var content = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
        //        var contentStream = new StreamReader(content);
        //        Constants.BillContent = contentStream.ReadToEnd();
        //    }
        //}

        //private string BuildBillForm()
        //{
        //    var sb = new StringBuilder(Constants.BillContent);
        //    sb.Replace(Properties.Resources.CSMS_Day, Convert.ToString(DateTime.Now.Day));
        //    sb.Replace(Properties.Resources.CSMS_Month, Convert.ToString(DateTime.Now.Month));
        //    sb.Replace(Properties.Resources.CSMS_Year, Convert.ToString(DateTime.Now.Year));
        //    sb.Replace(Properties.Resources.CSMS_Hour, Convert.ToString(DateTime.Now.Hour));
        //    sb.Replace(Properties.Resources.CSMS_Min, Convert.ToString(DateTime.Now.Minute));
        //    sb.Replace(Properties.Resources.PSM_Game_Money, txtGameMoney.Text);
        //    sb.Replace(Properties.Resources.PSM_Service_Money, txtAdditionalItemMoney.Text);
        //    sb.Replace(Properties.Resources.CSMS_Total_Products, txtTotalProduct.Text);
        //    sb.Replace(Properties.Resources.CSMS_Total_Money, txtTotalPrice.Text);
        //    sb.Replace(Properties.Resources.PSM_User, Constants.StaffName);
        //    sb.Replace(Properties.Resources.PSM_DeskName, lblDeskName.Text);

        //    return sb.ToString();
        //}

        private void txtID_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                btnSearch_Click(sender, e);
        }

        private void txtVipCodeCheck_Leave(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtVipCodeCheck.Text.Trim()))
            {
                if (!customersMng.CheckVipCode(txtVipCodeCheck.Text.Trim()))
                {
                    txtVipCodeCheck.ForeColor = Color.Red;
                    txtVipCodeCheck.Focus();
                }
                else
                {
                    txtVipCodeCheck.ForeColor = Color.DodgerBlue;
                    if (!IsDiscount && txtTotalPrice.Text == "0")
                    {
                        var discount = Convert.ToDecimal(Utilities.GetVipDiscount());
                        if (!string.IsNullOrEmpty(txtTotalCost.Text))
                        {
                            var cost = Convert.ToDecimal(txtTotalCost.Text.Trim()) -
                            (Convert.ToDecimal(txtTotalCost.Text.Trim()) * discount / 100);
                            txtTotalCost.Text = Utilities.FormatNumber(cost, Utilities.PrecisionFormat);
                        }
                        IsDiscount = true;
                        PercentDiscount = discount;
                    }
                    else
                        if (!IsDiscount && txtTotalPrice.Text != "0")
                        {
                            var discount = Convert.ToDecimal(Utilities.GetVipDiscount());
                            var cost = Convert.ToDecimal(txtTotalPrice.Text.Trim()) - (Convert.ToDecimal(txtTotalPrice.Text.Trim()) * discount / 100);
                            txtDiscountTotal.Text = Utilities.FormatNumber(cost, Utilities.PrecisionFormat);
                            lblDiscount.Text = String.Format("{0} % = {1}", discount, Utilities.FormatNumber((Convert.ToDecimal(txtTotalPrice.Text.Trim()) * discount / 100), Utilities.PrecisionFormat));
                            IsDiscount = true;
                            PercentDiscount = discount;
                        }
                        else
                        {
                            txtDiscountTotal.Text = txtTotalPrice.Text;
                        }
                    // Load customer
                    var customer = customersMng.GetItemByVipCode(txtVipCodeCheck.Text.Trim());
                    if (customer != null)
                    {
                        _customerInfo[0] = customer.ID;
                        _customerInfo[1] = txtCusName.Text = customer.Name;
                        _customerInfo[2] = customer.Address;
                        _customerInfo[3] = customer.PhoneNo;
                        _customerInfo[4] = customer.Email;
                        _customerInfo[5] = Convert.ToBoolean(customer.IsVip) ? "True" : "False";
                        _customerInfo[6] = customer.VipCode;
                    }
                }
            }
            if (string.IsNullOrEmpty(txtVipCodeCheck.Text.Trim()))
            {
                if (!string.IsNullOrEmpty(txtTotalCost.Text.Trim()) && PercentDiscount != 0 && txtTotalPrice.Text == "0" )
                {
                    var tmp = 100 - Convert.ToDecimal(PercentDiscount);
                    txtTotalCost.Text = Utilities.FormatNumber(Convert.ToDecimal(txtTotalCost.Text.Trim()) * 100 / tmp, Utilities.PrecisionFormat);
                }
                txtDiscountTotal.Text = txtTotalPrice.Text;
                lblDiscount.Text = Utilities.FormatNumber(0, Utilities.PrecisionFormat) + "%";
                PercentDiscount = 0;
                for (var i = 0; i < _customerInfo.Length; i++ )
                {
                    if (i == 5)
                        _customerInfo[i] = "False";
                    else
                        _customerInfo[i] = "";
                }
                txtCusName.Text = "";
                IsDiscount = false;
            }
        }

        private decimal currentRow = 0;
        private void gridCart_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 2)
            {
                foreach (DataGridViewRow row in gridCart.Rows)
                {
                    //foreach (DataGridViewCell cell in row.Cells)
                    //{
                    if (row.Index == currentRow)
                    {
                        //row.Selected = true;
                        if (Convert.ToDecimal(row.Cells[2].Value) > Convert.ToDecimal(row.Cells[5].Value))
                            row.Cells[2].Value = row.Cells[5].Value;
                        break;
                    }
                    // }
                }

                decimal totalprice = 0;
                decimal totalquantity = 0;
                foreach (DataGridViewRow row in gridCart.Rows)
                {
                    if (row.Index == currentRow)
                    {
                        var newPrice = Convert.ToDecimal(row.Cells[3].Value) / currentQty * Convert.ToDecimal(row.Cells[2].Value);
                        row.Cells[3].Value = newPrice;
                    }

                    totalquantity += Convert.ToDecimal(row.Cells[2].Value);
                    totalprice += Convert.ToDecimal(row.Cells[3].Value);
                }

                _totalCost = totalprice;
                _totalQty = totalquantity;
                txtTotalProduct.Text = Convert.ToString(totalquantity);
                txtTotalPrice.Text = Utilities.FormatNumber(totalprice, Utilities.PrecisionFormat);
                if (!string.IsNullOrEmpty(txtVipCodeCheck.Text.Trim()) && PercentDiscount != 0)
                {
                    var discountTotal = Convert.ToDecimal(txtTotalPrice.Text) -
                    (Convert.ToDecimal(txtTotalPrice.Text) * Convert.ToDecimal(PercentDiscount) / 100);
                    txtDiscountTotal.Text = Utilities.FormatNumber(discountTotal, Utilities.PrecisionFormat);
                    lblDiscount.Text = String.Format("{0}% = {1}", PercentDiscount, Utilities.FormatNumber((Convert.ToDecimal(txtTotalPrice.Text) * Convert.ToDecimal(PercentDiscount) / 100), Utilities.PrecisionFormat));
                }
                else
                {
                    txtDiscountTotal.Text = txtTotalPrice.Text;
                }
            }
        }

        private decimal currentQty;
        private void gridCart_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.ColumnIndex == 2)
            {
                foreach (DataGridViewRow row in gridCart.Rows)
                {
                    if (row.Cells[2].Selected)
                    {
                        row.Selected = true;
                        break;
                    }
                }
                if (Convert.ToDecimal(gridCart.SelectedCells[2].Value) == 0)
                {
                    currentQty = 1;
                    return;
                }
                currentRow = e.RowIndex;
                currentQty = Convert.ToDecimal(gridCart.SelectedCells[2].Value);
            }
        }

        private void gridInventoryList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && gridInventoryList.Rows[e.RowIndex].Selected)
            {
                string productCode = gridInventoryList.Rows[e.RowIndex].Cells[0].Value + "";
                if (!string.IsNullOrEmpty(productCode))
                {
                    var item = inventoryMng.GetInventoryByElements(productCode);
                    BindDataToTextbox(item.Name, Convert.ToString(item.Volume), item.ID, item.SupplierID, item.Category, item.StyleId, Convert.ToString(item.SalePrice), item.Image,
                    Convert.ToString(item.ImportPrice), Convert.ToString(item.Weight), Convert.ToDecimal(item.Quantity), item.InvoiceNo, item.ItemNo, item.MemoNo, item.StyleNo);
                    //Set max value for quantity
                    txtQuantity.Maximum = Convert.ToDecimal(item.Quantity);
                }
            }
        }

        private void gridCart_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 4)
            {
                DataGridViewRow row = gridCart.Rows[e.RowIndex];
                if (row.Cells[4].Selected)
                {
                    row.Selected = true;
                    RemoveCartItem(row);
                    txtTotalPrice.Text = Utilities.FormatNumber(Convert.ToDecimal(_totalCost), Utilities.PrecisionFormat);
                    txtTotalProduct.Text = Convert.ToString(_totalQty);
                }
            }
        }

        public void frmSellInventory_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F9)
            {
                btnBigSell_Click(sender, e);
            }
            else if(e.KeyCode == Keys.F10)
            {
                btnSaveDraft_Click(sender, e);
            }
        }

        

        //private void txtChiVang_Leave(object sender, EventArgs e)
        //{
        //    decimal chi = 0;
        //    try
        //    {
        //        chi = Convert.ToDecimal(txtChiVang.Text.Trim());
        //    }
        //    catch (FormatException)
        //    {
        //        txtChiVang.Text = "";
        //        return;
        //    }
        //    if (!string.IsNullOrEmpty(txtChiVang.Text.Trim()))
        //    {
        //        var convertedVal = chi * (decimal)Constants.GoldConst;
        //        txtWeight.Text = Utilities.FormatNumber(convertedVal, 3);
        //    }
        //    var total = Convert.ToDouble(txtImportPrice.Text) * Convert.ToDouble(txtWeight.Text.Trim()) /
        //                          Constants.GoldConst;
        //    lblCalImportPrice.Text = Utilities.FormatNumber(Convert.ToDecimal(total), Utilities.PrecisionFormat);
        //}

        //private void txtWeight_Leave_1(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        var a = Convert.ToDecimal(txtWeight.Text.Trim());

        //    }catch(FormatException)
        //    {
        //        txtWeight.Text = "";
        //        return;
        //    }
        //    txtWeight.Text = Utilities.FormatNumber(Convert.ToDecimal(txtWeight.Text.Trim()), 3);
        //    if (!string.IsNullOrEmpty(txtWeight.Text.Trim()))
        //    {
        //        var convertedVal = Convert.ToDecimal(txtWeight.Text) / (decimal)Constants.GoldConst;
        //        txtChiVang.Text = Utilities.FormatNumber(convertedVal, 3);
        //    }
        //    if (!string.IsNullOrEmpty(txtImportPrice.Text))
        //    {
        //        var total = Convert.ToDouble(txtImportPrice.Text)*Convert.ToDouble(txtQuantity.Text.Trim());
        //        lblCalImportPrice.Text = Utilities.FormatNumber(Convert.ToDecimal(total), Utilities.PrecisionFormat);
        //    }
        //}
    }
}
